package com.watson.onebox.sc.springbox;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.TriggerContext;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.PeriodicTrigger;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @program: LATSDataCollectAndExport
 * @description: DynamicScheduleTaskSecond
 * @author: zhangpeng348@jd.com
 * @date: 2019-04-26 17:40
 **/
@Component
@EnableScheduling
public class DynamicScheduleTaskSecond implements SchedulingConfigurer {
    private static final long WEEK_MILLIS = 604800000;
    private static final long MIN_MILLIS = 1000;
    private static long period = 1000;
    static long l = System.currentTimeMillis();

    @Autowired
    SetPeriod setPeriod;

    public static long getPeriod() {
        return period;
    }

    public static void setPeriod(long period) {
        DynamicScheduleTaskSecond.period = period;
    }

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        taskRegistrar.addTriggerTask(new Runnable() {
            @Override
            public void run() {
                try {
                    setPeriod.update(period);
                    System.out.println("abc");
                    Long last = System.currentTimeMillis() - l;
                    l = System.currentTimeMillis();
                    System.out.println(last);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }, new Trigger() {
            @Override
            public Date nextExecutionTime(TriggerContext triggerContext) {
                if (period < MIN_MILLIS || period > WEEK_MILLIS)
                    period = MIN_MILLIS;
                PeriodicTrigger periodicTrigger = new PeriodicTrigger(period);
                Date nextExecDate = periodicTrigger.nextExecutionTime(triggerContext);
                return nextExecDate;
            }
        });
    }
}
